package www.openteam.com.ui;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.tool.ScanType;
import www.openteam.com.zxing.ScanListener;
import www.openteam.com.zxing.ScanManager;
import www.openteam.com.zxing.decode.DecodeThread;
import www.openteam.com.zxing.decode.Utils;

public class ScanActivity
        extends AppCompatActivity implements ScanListener, View.OnClickListener {

    static final String TAG = ScanActivity.class.getSimpleName();
    SurfaceView scanPreView = null;
    View scanContainer;
    View scanCropView;
    ImageView scanLine;
    ScanManager scanManager;

    ImageView scan_image;
    @Bind(R.id.ic_back)
    ImageView ic_back;
    @Bind(R.id.ic_light)
    ImageView ic_light;
    @Bind(R.id.tv_result)
    TextView tv_result;
    @Bind(R.id.tv_hint)
    TextView tv_hint;
    @Bind(R.id.re_scan_button)
    Button rescan;
    @Bind(R.id.ok_scan_button)
    Button ok_scan_button;
    @Bind(R.id.tv_result_title)
    TextView tv_result_title;
    final int PHOTOREQUESTCODE = 1111;
    private int scanMode;//扫描模型（条形，二维码，全部）
    int RESULT_WO_ID= 1111;
    int RESULT_WO_MID=1112;
    int RECEIVE_ID=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_scan);
        ButterKnife.bind(this);
        scanMode = ScanType.REQUEST_SCAN_MODE_ALL_MODE;
        initView();
    }

    private void initView() {

        scanPreView = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_preview);
        scanCropView = findViewById(R.id.middle_san);
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);
        scan_image = (ImageView) findViewById(R.id.scan_image);
        ic_back.setOnClickListener(this);
        ic_light.setOnClickListener(this);
        tv_result.setVisibility(View.GONE);
        tv_result_title.setVisibility(View.GONE);
        rescan.setOnClickListener(this);
        ok_scan_button.setOnClickListener(this);
        scanManager = new ScanManager(this, scanPreView, scanContainer, scanCropView, scanLine, scanMode, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        scanManager.onResume();
        rescan.setVisibility(View.GONE);
        scan_image.setVisibility(View.INVISIBLE);
        ok_scan_button.setVisibility(View.GONE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: sa");
        scanManager.onPause();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {

            case R.id.ic_back:
                returnResult(RECEIVE_ID);
                break;
            case R.id.ic_light:
                scanManager.switchLight();
                break;
            case R.id.re_scan_button:
                startScan();
                break;
            case R.id.ok_scan_button:
                returnResult(RECEIVE_ID);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {

            returnResult(RECEIVE_ID);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }


    private void returnResult(int code) {

            Bundle bundle = new Bundle();
            bundle.putString("work_order_id", tv_result.getText().toString());
            setResult(code, this.getIntent().putExtras(bundle));
            finish();

        }

    private void startScan() {
        if (rescan.getVisibility() == View.VISIBLE) {
            rescan.setVisibility(View.GONE);
            ok_scan_button.setVisibility(View.GONE);
            scan_image.setVisibility(View.INVISIBLE);
            tv_result.setVisibility(View.GONE);
            tv_result_title.setVisibility(View.GONE);
            scanManager.reScan();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photo_path;
        RECEIVE_ID=requestCode;
        Log.d(TAG, "onActivityResult: "+requestCode+":"+resultCode);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                default:
                    Log.d(TAG, "onActivityResult: sa");
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(colum_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
                        }
                        scanManager.scanningImage(photo_path);
                    }

            }
            }
        }

        @Override
        public void scanResult (Result rawResult, Bundle bundle){
            if (!scanManager.isScanning()) {
                scan_image.setVisibility(View.VISIBLE);
                rescan.setVisibility(View.VISIBLE);
                tv_result_title.setVisibility(View.VISIBLE);
                ok_scan_button.setVisibility(View.VISIBLE);
                Bitmap bitmap = null;
                byte[] compressBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
                if (compressBitmap != null) {
                    bitmap = BitmapFactory.decodeByteArray(compressBitmap, 0, compressBitmap.length, null);
                    bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                }
                scan_image.setImageBitmap(bitmap);
            }
            scan_image.setVisibility(View.VISIBLE);
            ok_scan_button.setVisibility(View.VISIBLE);
            tv_result_title.setVisibility(View.VISIBLE);
            tv_result.setVisibility(View.VISIBLE);
            tv_result.setText(rawResult.getText());
        }

        @Override
        public void scanError (Exception exception){
            Toast.makeText(this, exception.getMessage(), Toast.LENGTH_LONG).show();
            //相机扫描出错时
            if (exception.getMessage() != null && exception.getMessage().startsWith("相机")) {
                scanPreView.setVisibility(View.INVISIBLE);
            }
        }
    }
